package cn.kgc.itrip.auth.controller;

import cn.kgc.itrip.auth.service.UserService;
import cn.kgc.itrip.beans.dto.Dto;
import cn.kgc.itrip.beans.pojo.ItripUser;
import cn.kgc.itrip.beans.vo.userinfo.ItripUserVO;
import cn.kgc.itrip.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(tags = "注册控制器")
@RestController
@RequestMapping("/api")
public class RegisterController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "手机号注册用户激活",
                  notes = "手机号注册的用户可以根据手机号和激活码进行用户激活。<br/>" +
                          "成功：success='true' | 失败：success='false' 和 错误代码，错误码如下：<br/>" +
                          "<ul>" +
                            "<li>300003：手机号格式错误</li>" +
                            "<li>300001：用户已经激活</li>" +
                            "<li>300007：用户还未注册</li>" +
                            "<li>300004：激活码已经过期</li>" +
                            "<li>300000：激活失败</li>" +
                          "</ul>",
                  produces = "application/json;charset=UTF-8"
                 )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "激活码", required = true, paramType = "query")
    })
    @RequestMapping(value = "/validatephone",method = RequestMethod.PUT)
    public Dto doValidatePhone(@RequestParam String user,@RequestParam String code){
        try {
            // 表单验证
            if(!ValidateUtil.validPhone(user)){
                return DtoUtil.returnFail("手机号格式错误！",ErrorCode.AUTH_PARAMETER_ERROR);
            }

            // 验证手机号是否注册过
            ItripUser itripUser = userService.checkUserIsExists(user);
            if(EmptyUtils.isNotEmpty(itripUser.getUserCode())){
                // 是否激活过
                if(itripUser.getActivated() == 1){
                    return DtoUtil.returnFail("该用户已经激活过！请勿重复激活！",ErrorCode.AUTH_USER_ALREADY_EXISTS);
                }
            }else{
                return DtoUtil.returnFail("该用户还未注册！请先去注册！",ErrorCode.AUTH_ILLEGAL_USERCODE);
            }

            // 验证激活码(等后面接入Redis)
            /*HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext application = request.getServletContext();
            Object obj = application.getAttribute("active:" + itripUser.getUserCode());
            String activeCode = (String)obj;*/
            // 接入Redis
            if(!userService.checkActiveCode(user,code)){
                return DtoUtil.returnFail("激活码错误或已经过期！",ErrorCode.AUTH_ACTIVATE_FAILED);
            }
            // 进行用户信息激活
            userService.activeUser(itripUser);
            return DtoUtil.returnSuccess();
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("激活失败！",ErrorCode.AUTH_UNKNOWN);
        }
    }

    // @ApiIgnore 添加此注解，则此接口将会被忽略
    @ApiOperation(
            value = "用户手机号注册",
            notes = "用户填写手机号进行注册，会收到注册激活码。<br/>" +
                    "成功：success='true' | 失败：success='false' 且返回错误代码，错误码如下：<br/>" +
                    "<ul>" +
                        "<li>300003：注册参数错误</li>" +
                        "<li>300001：用户已经注册</li>" +
                        "<li>300000：注册失败</li>" +
                    "</ul>",
            produces = "application/json;charset=UTF-8"
    )
    @RequestMapping(value = "/registerbyphone",method = RequestMethod.POST)
    public Dto doRegisterByPhone(@RequestBody ItripUserVO vo){
        try {
            // 表单验证
            if(!ValidateUtil.validPhone(vo.getUserCode()) || EmptyUtils.isEmpty(vo.getUserPassword())){
                return DtoUtil.returnFail("注册参数错误！",ErrorCode.AUTH_PARAMETER_ERROR);
            }
            // 验证手机号是否已经注册
            ItripUser itripUser = userService.checkUserIsExists(vo.getUserCode());
            if(EmptyUtils.isNotEmpty(itripUser.getUserCode())){
                // 验证是否已经激活
                if(itripUser.getActivated() == 1){
                    return DtoUtil.returnFail("用户已经注册！",ErrorCode.AUTH_USER_ALREADY_EXISTS);
                }
            }
            // 用户注册实现(可以重发激活码)
            itripUser.setUserCode(vo.getUserCode());
            itripUser.setUserName(vo.getUserName());
            itripUser.setUserPassword(MD5.getMd5(vo.getUserPassword(),32));
            userService.registerUser(itripUser);
            return DtoUtil.returnSuccess();
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("注册失败！", ErrorCode.AUTH_UNKNOWN);
        }
    }

    @RequestMapping(value = "/ckusr", method = RequestMethod.GET)
    public Dto doEmail(String name){
        return DtoUtil.returnSuccess();
    }

    @RequestMapping(value = "/doregister", method = RequestMethod.POST)
    public Dto doEmailBy(@RequestBody ItripUserVO vo){
        try {
            // 表单验证
            if(!ValidateUtil.validEmail(vo.getUserCode()) || EmptyUtils.isEmpty(vo.getUserPassword())){
                return DtoUtil.returnFail("注册参数错误！",ErrorCode.AUTH_PARAMETER_ERROR);
            }
            // 验证手机号是否已经注册
            ItripUser itripUser = userService.checkUserIsExists(vo.getUserCode());
            if(EmptyUtils.isNotEmpty(itripUser.getUserCode())){
                // 验证是否已经激活
                if(itripUser.getActivated() == 1){
                    return DtoUtil.returnFail("用户已经注册！",ErrorCode.AUTH_USER_ALREADY_EXISTS);
                }
            }
            // 用户注册实现(可以重发激活码)
            itripUser.setUserCode(vo.getUserCode());
            itripUser.setUserName(vo.getUserName());
            itripUser.setUserPassword(MD5.getMd5(vo.getUserPassword(),32));
            userService.doRegisterUser(itripUser);
            return DtoUtil.returnSuccess();
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("注册失败！", ErrorCode.AUTH_UNKNOWN);
        }
    }

    @RequestMapping(value = "/activate",method = RequestMethod.PUT)
    public Dto doActivate(@RequestParam String user,@RequestParam String code){
        try {
            // 表单验证
            if(!ValidateUtil.validEmail(user)){
                return DtoUtil.returnFail("邮箱格式错误！",ErrorCode.AUTH_PARAMETER_ERROR);
            }
            // 验证邮箱是否注册过
            ItripUser itripUser = userService.checkUserIsExists(user);
            if(EmptyUtils.isNotEmpty(itripUser.getUserCode())){
                // 是否激活过
                if(itripUser.getActivated() == 1){
                    return DtoUtil.returnFail("该用户已经激活过！请勿重复激活！",ErrorCode.AUTH_USER_ALREADY_EXISTS);
                }
            }else{
                return DtoUtil.returnFail("该用户还未注册！请先去注册！",ErrorCode.AUTH_ILLEGAL_USERCODE);
            }
            if(!userService.checkActiveCode(user,code)){
                return DtoUtil.returnFail("激活码错误或已经过期！",ErrorCode.AUTH_ACTIVATE_FAILED);
            }
            // 进行用户信息激活
            userService.activeUser(itripUser);
            return DtoUtil.returnSuccess();
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("激活失败！",ErrorCode.AUTH_UNKNOWN);
        }
    }
}
